package com.furongji.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.furongji.common.domain.vo.UserSimpleVo;
import com.furongji.common.enums.ArticleStatusEnum;
import com.furongji.common.exception.MyException;
import com.furongji.common.utils.UserThreadLocalUtil;
import com.furongji.education.clients.UserFeignClient;
import com.furongji.education.domain.dto.ArticleDto;
import com.furongji.education.domain.po.Article;
import com.furongji.education.domain.query.ArticleQuery;
import com.furongji.education.domain.vo.ArticleVo;
import com.furongji.education.mapper.ArticleMapper;
import com.furongji.education.service.ArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 社区文章表 服务实现类
 * </p>
 *
 * @author furongji
 * @since 2025-06-05
 */
@Service
@RequiredArgsConstructor
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    private final UserFeignClient userClient;

    // 获取用户端文章列表
    @Override
    public IPage<ArticleVo> getArticles(Integer current, Integer size, ArticleQuery articleQuery) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(articleQuery.getUserName())) {
            queryWrapper.like(Article::getUserName, articleQuery.getUserName());
        }
        if (StringUtils.hasText(articleQuery.getTitle())) {
            queryWrapper.like(Article::getTitle, articleQuery.getTitle());
        }
        queryWrapper.eq(Article::getStatus, ArticleStatusEnum.Normal);
        queryWrapper.orderByDesc(Article::getGmtCreate);

        IPage<Article> articlePage = super.page(new Page<>(current, size), queryWrapper);

        List<Article> records = articlePage.getRecords();

        List<ArticleVo> resultList = records.stream().map(record -> {
//            List<String> imageUrlList = articleImageService.getImageUrlList(record.getId());
            ArticleVo articleVo = new ArticleVo(
                    null,
                    null,
                    record.getUserName(),
                    record.getId(),
                    record.getTitle(),
                    record.getContent(),
                    record.getCover(),
                    record.getViewCount(),
                    record.getLikeCount(),
                    50, // TODO 后续远程调用评论微服务
                    record.getGmtCreate()
            );
            return articleVo;
        }).toList();

        IPage<ArticleVo> resultPage = new Page<>();
        resultPage.setRecords(resultList);
        resultPage.setTotal(articlePage.getTotal());
        resultPage.setCurrent(articlePage.getCurrent());
        resultPage.setSize(articlePage.getSize());
        resultPage.setPages(articlePage.getPages());

        return resultPage;
    }

    // 用户发布文章
    @Override
    public boolean publishArticle(ArticleDto articleDto) throws JsonProcessingException {
        if (articleDto == null) {
            throw new MyException(20001, "文章对象不能为空");
        }
        if (!StringUtils.hasText(articleDto.getTitle())) {
            throw new MyException(20001, "文章标题不能为空");
        }
        if (!StringUtils.hasText(articleDto.getContent())) {
            throw new MyException(20001, "文章内容不能为空");
        }
        if (articleDto.getStatus() == null) {
            throw new MyException(20001, "文章发布状态不能为空");
        }
        if (!StringUtils.hasText(articleDto.getCover())) {
            throw new MyException(20001, "文章封面不能为空");
        }

        String title = articleDto.getTitle();
        String content = articleDto.getContent();
        ArticleStatusEnum status = articleDto.getStatus();
        String cover = articleDto.getCover();
        String userId = new ObjectMapper()
                .readTree(UserThreadLocalUtil.getUser())
                .get("userId")
                .asText();
        if (!StringUtils.hasText(userId)) {
            throw new MyException(20001, "未登录不能发表文章");
        }
        UserSimpleVo userSimple = userClient.getNameAndAvatar(userId);

        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setCover(cover);
        article.setUserId(userId);
        article.setUserName(userSimple.getUsername());
        article.setUserAvatar(userSimple.getAvatar());
        article.setStatus(status);

        return super.save(article);
    }

    @Override
    public ArticleVo getArticleInfo(String articleId) {
        Article article = super.getById(articleId);
        ArticleVo articleVo = new ArticleVo(
                article.getUserId(),
                article.getUserName(),
                article.getUserAvatar(),
                article.getId(),
                article.getTitle(),
                article.getContent(),
                article.getCover(),
                article.getViewCount(),
                article.getLikeCount(),
                50, //TODO 后续远程调用评论模块
                article.getGmtCreate()
        );
        return articleVo;
    }
}
